const rp = require('request-promise');
const AppID = 'xxx';
const AppSecret = 'xxx';

const getWXUserInfo = (code, appid, secret) => {
  return new Promise((resolve, reject) => {
    getWXToken(code)
      .then(data => {
        request(`https://api.weixin.qq.com/sns/userinfo?access_token=${data.access_token}&openid=${data.openid}`)
          .then(data => resolve(JSON.parse(data)))
          .catch(err => reject(err))
      }).catch(err => reject(err))
  })
}

const getWXToken = (code, appid, secret) => {
  return new Promise((resolve, reject) => {
    const token_url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
    // const token_url =`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
    rp(token_url)
      .then(data => {
        data = JSON.parse(data)
        console.log('data',data);
        if (!data.openid || !data.session_key) {
          reject({code:110, error:'Authenticate failed in WeChat.'});
        }
        resolve(data)
      }).catch(err => reject(err));
  })
}

const getUser = async (req, res, next) => {
  console.log('cookies',req.cookies);
  const path = req.path;
  if(req.method === 'GET'){
  // if(path.indexOf('/person/number') > -1){
    // console.log('path',path.indexOf('/person/number'));
    next();
  }else{
    const openid = req.cookies.openid;
    if(openid){
      req.user = {
        openid:openid
      }
      next();
    }else{
      const {code} = req.body;
      console.log('code',code);
      if(code){
        try{
          const data = await getWXToken(code,AppID,AppSecret);
          req.user = {
            session:data.session_key,
            openid:data.openid
          }
          console.log('user',req.user);
          next();
        }catch(err){
          res.reply(err);
        }
      }else{
        res.reply({code:101, error:'Code is needed.Please quit and re-enter.'});
      }
    }
  } 
}

module.exports = { getUser };
